<template>
  <div class="followup-box inner-content">
    <div class="inner inner-content-box">
      <div class="searchBox">
        <el-form
          :inline="true"
          :model="searchForm"
          size="small"
          style="width: 100%"
        >
          <el-form-item label="学生库名称">
            <el-input
              v-model="searchForm.studentPool"
              placeholder="学生库名称"
              clearable
              style="width: 120px"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              @click="getList"
              size="small"
              icon="el-icon-search"
              >搜索</el-button
            >
            <el-button @click="searchReset" size="small" icon="el-icon-delete"
              >清空</el-button
            >
          </el-form-item>
          <br />
          <el-form-item>
            <el-button
              v-if="isAuth('examinee:list:add')"
              size="small"
              type="primary"
              @click="add"
            >
              <span class="icon iconfont icon-friends-o"></span>
              新增考生库
            </el-button>
            <el-button
              v-if="isAuth('examinee:list:delete')"
              size="small"
              type="danger"
              @click="delHandle('branch')"
              :disabled="dataSelect.length == 0"
            >
              <span class="el-icon-delete"></span>
              删除
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="detailsBox">
        <ag-grid-vue
          class="ag-theme-alpine ag-theme-quartz"
          :gridOptions="gridOptions"
          :localeText="localeText"
          @grid-ready="onGridReady"
          @selection-changed="getSelectedRows"
          @sort-changed="onSortChangedAggrid"
          @filter-changed="onFilterChangedAggrid"
          :rowHeight="38"
          :headerHeight="42"
          :columnDefs="columnDefs"
          :defaultColDef="defaultColDef"
          :rowData="rowData"
          rowSelection="multiple"
          :rowMultiSelectWithClick="true"
          :enableRangeSelection="true"
        >
        </ag-grid-vue>
      </div>
      <div class="pageBox">
        <div>
          选择 <strong style="color: #00b99e;">{{ dataSelect.length }}</strong> 数据
        </div>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.currentPage"
          :page-sizes="page.pageSizes"
          :page-size="page.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total"
        >
        </el-pagination>
      </div>
    </div>
    <el-dialog
      :title="addOrUpdateFlag === 'add' ? '新增考生库' : '编辑考生库'"
      :visible.sync="addOrUpdateVisible"
      width="600px"
      size="small"
      :before-close="handleClose">
      
      <el-form :model="addOrUpdateForm" :rules="addOrUpdateFormRules" ref="addOrUpdateForm" label-width="240px" style="width: 500px">
        <el-form-item label="考生库名称：" prop="studentPool">
          <el-input v-model="addOrUpdateForm.studentPool"  placeholder="考生库名称"></el-input>
        </el-form-item>
        <el-form-item label="考试类型：" prop="type">
          <el-select v-model="addOrUpdateForm.type" size="small" style="width: 100%;">
              <el-option v-for="(item,index) in typeList" :key="index" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="考生类别：" prop="category">
          <el-select v-model="addOrUpdateForm.category" size="small" style="width: 100%;">
              <el-option v-for="(item,index) in categoryList" :key="index" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否根据导入的学生数据进行分组：" prop="ifOrder">
          <!-- {{ exercisesForm.ifOrder   true: 1 是   false： 0 否 }} -->
          <el-switch
            v-model="addOrUpdateForm.ifOrder"
            active-text="是"
            inactive-text="否">
          </el-switch>
        </el-form-item>
        <el-form-item label="是否需要密码：" prop="passwordType">
          <!-- {{ exercisesForm.passwordType   true: 1 需要密码   false： 0 不需要密码 }} -->
          <el-switch
            v-model="addOrUpdateForm.passwordType"
            :disabled="addOrUpdateForm.id && addOrUpdateForm.createUserId !== userInfo.id"
            active-text="需要"
            inactive-text="不需要">
          </el-switch>
        </el-form-item>
        <el-form-item label="密码：" prop="password" v-if="addOrUpdateForm.passwordType == true">
          <el-input type="password" style="width: 240px" v-model="addOrUpdateForm.password" autocomplete="off" placeholder="请输入密码" :disabled="addOrUpdateForm.id && addOrUpdateForm.createUserId !== userInfo.id"></el-input>
        </el-form-item>
        <el-form-item label="确认密码：" prop="checkPassword" v-if="addOrUpdateForm.passwordType == true">
          <el-input type="password" style="width: 240px" v-model="addOrUpdateForm.checkPassword" autocomplete="off" placeholder="请再次输入密码" :disabled="addOrUpdateForm.id && addOrUpdateForm.createUserId !== userInfo.id"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose" size="small" :loading='btnLoading'>取 消</el-button>
        <el-button type="primary" @click="submit('addOrUpdateForm')" size="small" :loading='btnLoading'>确 定</el-button>
      </span>
    </el-dialog>

    <addStudent ref='addStudent' :addVisable='addVisable' :examineeObj='examineeObj' @child-event="parentMethod"></addStudent>

    <editStudent ref='editStudent' :editVisable='editVisable' :examineeObj='examineeObj' @child-event="closeMethod"></editStudent>
    <el-dialog
      title="校验密码"
      :visible.sync="passwordVisible"
      width="500px"
      :before-close="handleClosePwd">
      <div>
        <el-form :model="passwordForm" :rules="passwordFormRules" ref="passwordForm" label-width="160px" style="padding-right: 30px;padding-top: 10px;" label-position="right">
          <el-form-item label="请输入密码：" prop="password">
            <el-input type="password" style="width: 240px" v-model="passwordForm.password" autocomplete="off" placeholder="请输入密码"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClosePwd">取 消</el-button>
        <el-button type="primary" @click="submitPassword('passwordForm')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
// import Vue from 'vue'
import listBtn from '@/views/modules/examinee/listBtn.vue'
import listJson from '@/views/modules/examinee/list.json'
import {fetchList, addObj, deleteObj, updateObj} from '@/api/examinee.js'
import { authCheck, initializePwd } from '@/api/index'
import { Message } from 'element-ui'
import addStudent from './addStudent.vue'
import editStudent from './editStudent.vue'
import studentList from './studentList.vue'
export default {
  beforeMount () {
    this.gridOptions = {
      // 通过这个属性建立了上下文引用
      context: { componentParent: this }
      // 说人话就是可以在自己声明的组件里调用到父组件的方法和属性了
    }
  },
  components: {
    listBtn,
    addStudent,
    editStudent,
    studentList
  },
  watch: {
    $route: {
      handler (newValue, oldValue) {
        if (oldValue.name === 'examinee-list') {
          this.addOrUpdateVisible = false
          this.passwordVisible = false
          this.addVisable = false
          this.editVisable = false
        }
      },
      deep: true
    }
  },
  data () {
    var validatePass = (rule, value, callback) => {
      console.log('value', value)
      if (value === '' || value === null) {
        callback(new Error('请输入密码'))
      } else {
        if (this.addOrUpdateForm.password !== '') {
          this.$refs.addOrUpdateForm.validateField('checkPassword')
        }
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.addOrUpdateForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      gridOptions: null,
      localeText: this.$AG_GRID_LOCALE_ZZZ,
      col: [],
      page: {
        pageSizes: [100, 2000, 5000],
        currentPage: 1,
        total: 0,
        pageSize: 100
      },
      searchForm: {
        hospNo: ''
      },
      defaultColDef: {
        editable: false,
        sortable: true,
        resizable: true,
        filter: true,
        cellDataType: false
      },
      typeList: [
        {
          value: 'A类',
          label: 'A类考试'
        },
        {
          value: 'B类',
          label: 'B类考试'
        }
      ],
      categoryList: [
        {
          value: '本科生',
          label: '本科生'
        },
        {
          value: '住院医师',
          label: '住院医师'
        }
      ],
      rowIndexArr: [
        {
          field: 'rowIndex',
          headerName: '序号',
          width: 100,
          checkboxSelection: true,
          headerCheckboxSelection: true,
          sortable: false,
          pinned: 'left',
          valueGetter: (params) => {
            // 返回当前行的序号
            return params.node.rowIndex + 1
          }
        },
        {
          field: 'handle',
          headerName: '操作',
          width: 200,
          pinned: 'right',
          cellRenderer: 'listBtn'
        }
      ],
      columnDefs: [],
      gridApi: null,
      rowData: [],
      dataSelect: [],

      // 新增
      addOrUpdateVisible: false,
      addOrUpdateFormBak: {
        studentPool: '',
        type: 'B类',
        passwordType: false,
        ifOrder: false,
        password: '',
        checkPassword: ''
      },
      addOrUpdateForm: {
        studentPool: '',
        type: 'B类',
        passwordType: false,
        ifOrder: false,
        password: '',
        checkPassword: ''
      },
      addOrUpdateFormRules: {
        studentPool: [
            { required: true, message: '请输入考生库名称', trigger: 'blur' }
        ],
        type: [
            { required: true, message: '请选择考试类型', trigger: 'blur' }
        ],
        category: [
            { required: true, message: '请选择考生类别', trigger: 'blur' }
        ],
        password: [
            { required: true, validator: validatePass, trigger: 'blur' }
        ],
        checkPassword: [
            { required: true, validator: validatePass2, trigger: 'blur' }
        ]
      },
      addOrUpdateFlag: 'add',
      btnLoading: false,
      msg: null,

      addVisable: false,
      editVisable: false,
      examineeObj: {},

      // 密码 start
      checkPasswork: '',
      passwordVisible: false,
      passwordForm: {
        password: ''
      },
      passwordFormRules: {
        password: [{ required: true, message: '密码不能为空', trigger: 'change' }]
      },
      passwordCheck: '',
      examinationIdDialog: '',
      // 下一步的操作
      byPwdFlag: '',
      userInfo: this.$store.state.user
      // 密码 end
    }
  },
  created () {
    this.getHeadersCol()
    setTimeout(() => {
      this.getList()
    }, 10)
  },
  methods: {
    onSortChangedAggrid (event) {
      const api = event.api
      const visibleRowCount = api.getDisplayedRowCount()
      for (let i = 0; i < visibleRowCount; i++) {
        const rowNode = api.getDisplayedRowAtIndex(i)
        console.log(rowNode)
      }
      let aaa = JSON.parse(JSON.stringify(this.rowData))
      if (this.gridApi.getRenderedNodes().length > 1) {
        this.aggridScrollNum = this.gridApi.getRenderedNodes()[1].rowIndex - 1
      } else {
        this.aggridScrollNum = this.gridApi.getRenderedNodes()[0].rowIndex
      }
      setTimeout(() => {
        this.rowData = JSON.parse(JSON.stringify(aaa))
        setTimeout(() => {
          if (this.aggridScrollNum !== 0) {
            this.gridApi.ensureIndexVisible(this.aggridScrollNum, 'top')
          }
        }, 10)
      }, 10)
    },
    onFilterChangedAggrid (event) {
      const api = event.api
      const visibleRowCount = api.getDisplayedRowCount()
      for (let i = 0; i < visibleRowCount; i++) {
        const rowNode = api.getDisplayedRowAtIndex(i)
        console.log(rowNode)
      }
      let aaa = JSON.parse(JSON.stringify(this.rowData))
      if (this.gridApi.getRenderedNodes().length > 1) {
        this.aggridScrollNum = this.gridApi.getRenderedNodes()[1].rowIndex - 1
      } else {
        this.aggridScrollNum = this.gridApi.getRenderedNodes()[0].rowIndex
      }
      setTimeout(() => {
        this.rowData = JSON.parse(JSON.stringify(aaa))
        setTimeout(() => {
          if (this.aggridScrollNum !== 0) {
            this.gridApi.ensureIndexVisible(this.aggridScrollNum, 'top')
          }
        }, 10)
      }, 10)
    },
    // 获取选中
    getSelectedRows () {
      this.dataSelect = this.gridApi.getSelectedRows()
    },
    // 获取表头
    getHeadersCol () {
      this.columnDefs = []
      setTimeout(() => {
        this.col = JSON.parse(JSON.stringify(listJson.column))
        this.columnDefs = this.rowIndexArr.concat(this.col)
      }, 10)
    },
    // 装载列表
    onGridReady (params) {
      this.gridApi = params.api
    },
    getList () {
      let params = {
        limit: this.page.pageSize,
        page: this.page.currentPage,
        orderSql: 'creat_date desc',
        studentPool: this.searchForm.studentPool || ''
      }
      fetchList(params).then(res => {
        this.rowData = res.data.page.records
        this.rowData.map(v => {
          v.ifOrderName = v.ifOrder === '1' ? '是' : '否'
        })
        this.page.total = res.data.page.total
        this.dataSelect = []
      })
    },
    handleSizeChange (val) {
      this.page.pageSize = val
      this.getList()
    },
    handleCurrentChange (val) {
      this.page.currentPage = val
      this.getList()
    },
    // 清空搜索
    searchReset () {
      this.searchForm = {}
      this.page.currentPage = 1
      // this.getList();
    },
    // 重制密码
    resetItem (val) {
      const h = this.$createElement
      this.$msgbox({
        title: '重置密码',
        message: h('p', null, [
          h('i', { class: 'icon iconfont icon-zhongzhimima', style: 'color: red;font-weight: 600;font-size: 20px !important;padding-right: 10px' }, ''),
          h('span', null, '此操作将重置密码！请确认是否继续')
        ]),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '操作中...'
            initializePwd({type: 3, id: val.id}).then(res => {
              if (res.data.code === 0) {
                this.$message.success('密码重置成功')
                done()
                setTimeout(() => {
                  instance.confirmButtonLoading = false
                }, 300)
              }
            })
          } else {
            done()
          }
        }
      })
    },
    // 通过密码查看
    passwordEdit (params) {
      this.passwordForm.password = ''
      this.examinationIdDialog = params.id
      this.addOrUpdateForm = JSON.parse(JSON.stringify(params))
      this.addOrUpdateFlag = 'edit'
      this.byPwdFlag = 'edit'
      this.passwordVisible = true
      setTimeout(() => {
        this.$refs['passwordForm'].resetFields()
      }, 10)
    },
    // 通过密码 删除
    delByPwdHandle (params) {
      this.passwordForm.password = ''
      this.examinationIdDialog = params.id
      this.addOrUpdateForm = JSON.parse(JSON.stringify(params))
      this.passwordVisible = true
      this.byPwdFlag = 'del'
      setTimeout(() => {
        this.$refs['passwordForm'].resetFields()
      }, 10)
    },
    // 通过密码 查看
    viewByPwdHandle (params) {
      this.passwordForm.password = ''
      this.examinationIdDialog = params.id
      this.addOrUpdateForm = JSON.parse(JSON.stringify(params))
      this.passwordVisible = true
      this.byPwdFlag = 'view'
      setTimeout(() => {
        this.$refs['passwordForm'].resetFields()
      }, 10)
    },
    // 通过密码 导入
    importByPwdHandle (params) {
      this.passwordForm.password = ''
      this.examinationIdDialog = params.id
      this.addOrUpdateForm = JSON.parse(JSON.stringify(params))
      this.passwordVisible = true
      this.byPwdFlag = 'import'
      setTimeout(() => {
        this.$refs['passwordForm'].resetFields()
      }, 10)
    },
    handleClosePwd () {
      this.passwordVisible = false
    },
    submitPassword (form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          let params = {
            id: this.examinationIdDialog,
            type: 3,
            passwordType: '1',
            password: this.passwordForm.password
          }
          this.passwordCheck = this.passwordForm.password
          console.log('this.passwordCheck', this.passwordCheck)
          authCheck(params).then(res => {
            if (res.data.code === 0) {
              this.$message.success(res.data.msg || '密码正确')
              if (this.byPwdFlag === 'edit') {
                setTimeout(() => {
                  this.$refs['passwordForm'].resetFields()
                  this.passwordVisible = false
                  this.addOrUpdateVisible = true
                  if (params.passwordType === '1') {
                    this.addOrUpdateForm.passwordType = true
                    this.addOrUpdateForm.password = this.passwordCheck
                    this.addOrUpdateForm.checkPassword = this.passwordCheck
                  } else {
                    this.addOrUpdateForm.passwordType = false
                  }
                  if (this.addOrUpdateForm.ifOrder === '1') {
                    this.addOrUpdateForm.ifOrder = true
                  } else {
                    this.addOrUpdateForm.ifOrder = false
                  }
                  let aaa = JSON.parse(JSON.stringify(this.addOrUpdateForm))
                  this.addOrUpdateForm = {}
                  this.addOrUpdateForm = JSON.parse(JSON.stringify(aaa))
                }, 1000)
              } else if (this.byPwdFlag === 'del') {
                this.$refs['passwordForm'].resetFields()
                this.passwordVisible = false
                this.delHandle(this.addOrUpdateForm)
              } else if (this.byPwdFlag === 'view') {
                this.$refs['passwordForm'].resetFields()
                this.passwordVisible = false
                this.viewHandle(this.addOrUpdateForm)
              } else if (this.byPwdFlag === 'import') {
                this.$refs['passwordForm'].resetFields()
                this.passwordVisible = false
                this.importHandle(this.addOrUpdateForm)
              }
            }
          })
        } else {
          return false
        }
      })
    },
    // handel
    edit (val) {
      this.addOrUpdateForm = JSON.parse(JSON.stringify(val))
      if (this.addOrUpdateForm.ifOrder === '1') {
        this.addOrUpdateForm.ifOrder = true
      } else {
        this.addOrUpdateForm.ifOrder = false
      }
      if (this.addOrUpdateForm.passwordType === '1') {
        this.addOrUpdateForm.passwordType = true
      } else {
        this.addOrUpdateForm.passwordType = false
      }
      this.addOrUpdateFlag = 'edit'
      console.log()
      this.addOrUpdateVisible = true
    },
    resetForm () {
      this.$refs['addOrUpdateForm'].resetFields()
    },
    // 新增编辑
    handleClose () {
      this.addOrUpdateForm = JSON.parse(JSON.stringify(this.addOrUpdateFormBak))
      this.resetForm()
      setTimeout(() => {
        this.addOrUpdateVisible = false
      }, 1)
    },
    add () {
      this.addOrUpdateFlag = 'add'
      this.addOrUpdateVisible = true
    },
    // 新增修改
    submit (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.btnLoading = true
          this.msg = Message({
            duration: 0,
            dangerouslyUseHTMLString: true,
            iconClass: 'el-icon-loading',
            message: '<p style="padding-left: 10px;">操作中，请稍后...</p>'
          })
          if (this.addOrUpdateFlag === 'add') {
            let params = {
              studentPool: this.addOrUpdateForm.studentPool,
              type: this.addOrUpdateForm.type,
              category: this.addOrUpdateForm.category,
              createUserId: this.userInfo.id,
              createUserName: this.userInfo.realName
            }
            if (this.addOrUpdateForm.passwordType) {
              params.password = this.addOrUpdateForm.password
              params.passwordType = '1'
            } else {
              params.passwordType = '0'
            }
            if (this.addOrUpdateForm.ifOrder) {
              params.ifOrder = '1'
            } else {
              params.ifOrder = '0'
            }
            addObj(params).then(res => {
              this.btnLoading = false
              this.handleClose()
              this.msg.close()
              this.$message.success('新增成功')
              this.getList()
            })
          } else {
            let params = {
              studentPool: this.addOrUpdateForm.studentPool,
              type: this.addOrUpdateForm.type,
              category: this.addOrUpdateForm.category,
              id: this.addOrUpdateForm.id
            }
            if (this.addOrUpdateForm.passwordType) {
              params.password = this.addOrUpdateForm.password
              params.passwordType = '1'
            } else {
              params.passwordType = '0'
            }
            if (this.addOrUpdateForm.ifOrder) {
              params.ifOrder = '1'
            } else {
              params.ifOrder = '0'
            }
            if (this.passwordCheck !== '') {
              params.passwordCheck = this.passwordCheck
            }
            updateObj(params).then(res => {
              console.log(res)
              this.btnLoading = false
              this.handleClose()
              this.msg.close()
              this.$message.success('编辑成功')
              this.getList()
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 删除
    delHandle (val) {
      let msg = val === 'branch' ? '选中数据' : val.studentPool
      let params = val === 'branch' ? this.dataSelect.map(item => {
        return item.id
      }) : [val.id]
      console.log(params)
      const h = this.$createElement
      this.$msgbox({
        title: '提示',
        message: h('p', { class: 'flex', style: 'justify-content:flex-start;width: 400px' }, [
          h(
            'i',
            {
              class: 'el-icon-delete-solid',
              style: 'color: #ff0000b5;font-size: 26px;padding-right: 10px'
            },
            ''
          ),
          h('span', null, `此操作将删除“${msg}”`)
        ]),
        showCancelButton: true,
        closeOnClickModal: false,
        closeOnPressEscape: false,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '删除中...'
            deleteObj(params)
              .then(res => {
                done()
                instance.confirmButtonLoading = false
                if (res.data.code === 0) {
                  this.$message.success('删除成功')
                  this.getList()
                }
              })
              .catch(() => {
                instance.confirmButtonLoading = false
                done()
              })
          } else {
            done()
          }
        }
      })
    },

    // 导入
    importHandle (val) {
      this.examineeObj = JSON.parse(JSON.stringify(val))
      this.addVisable = true
      this.$refs.addStudent.resetList()
    },

    // 编辑查看
    viewHandle (val) {
      this.examineeObj = JSON.parse(JSON.stringify(val))
      this.editVisable = true
      setTimeout(() => {
        this.$refs.editStudent.getStudentList()
      }, 10)
    },

    parentMethod () {
      this.addVisable = false
      this.getList()
    },
    closeMethod () {
      this.editVisable = false
      this.getList()
    }
  }
}
</script>
